import { ConfigPlugin, createRunOncePlugin, withAndroidManifest, withInfoPlist } from '@expo/config-plugins';

/**
 * 使用DLNA Player插件所需的配置选项
 */
export interface DlnaPlayerPluginProps {
  /**
   * 指定是否添加网络相关权限
   * @default true
   */
  includeNetworkPermissions?: boolean;
}

/**
 * 为Android配置DLNA播放器所需的权限
 */
const withAndroidPermissions = (config: any, { includeNetworkPermissions = true } = {}) => {
  return withAndroidManifest(config, async (config: any) => {
    const { modResults } = config;

    // 确保有uses-permission节点
    if (!Array.isArray(modResults.manifest['uses-permission'])) {
      modResults.manifest['uses-permission'] = [];
    }

    const permissions = modResults.manifest['uses-permission'];
    
    // 添加所需的权限
    if (includeNetworkPermissions) {
      const PERMISSIONS = [
        'android.permission.INTERNET',
        'android.permission.ACCESS_NETWORK_STATE',
        'android.permission.ACCESS_WIFI_STATE',
        'android.permission.CHANGE_WIFI_MULTICAST_STATE',
      ];

      // 添加权限（如果不存在）
      PERMISSIONS.forEach((permission) => {
        const existingPermission = permissions.find(
          (item: any) => item.$?.['android:name'] === permission
        );

        if (!existingPermission) {
          permissions.push({
            $: {
              'android:name': permission,
            },
          });
        }
      });
    }

    return config;
  });
};

/**
 * 为iOS配置DLNA播放器所需的权限和设置
 */
const withIosPermissions: ConfigPlugin<DlnaPlayerPluginProps> = (config: any) => {
  return withInfoPlist(config, (config: any) => {
    const { modResults } = config;

    // 添加本地网络使用权限描述
    if (!modResults.NSLocalNetworkUsageDescription) {
      modResults.NSLocalNetworkUsageDescription = '允许应用在本地网络上发现可用的DLNA/AirPlay设备';
    }

    // 添加隐私 - 本地网络使用权限
    if (!modResults.NSBonjourServices) {
      modResults.NSBonjourServices = ['_googlecast._tcp', '_airplay._tcp'];
    }

    // 支持AirPlay
    if (modResults.UIBackgroundModes?.indexOf('audio') === -1) {
      if (!modResults.UIBackgroundModes) {
        modResults.UIBackgroundModes = [];
      }
      modResults.UIBackgroundModes.push('audio');
    }

    return config;
  });
};

/**
 * 配置Expo应用以支持DLNA播放器
 */
const withDlnaPlayer: ConfigPlugin<DlnaPlayerPluginProps> = (
  config: any,
  props = {}
) => {
  config = withAndroidPermissions(config, props);
  config = withIosPermissions(config, props);
  return config;
};

export default createRunOncePlugin(
  withDlnaPlayer,
  'react-native-dlna-player',
  '0.7.0' // 版本号应与插件版本一致
); 